/**
 * @description order 
 */
const { Order, Product, Address } = require('../models/index')
/**
 * 创建订单
 * @param {String} username 
 * @param {Object} data 
 * @returns 
 */
async function createOrder(username, data) {
  const {
    addressId,
    shopId,
    shopName,
    isCanceled = false,
    products = []
  } = data

  //根据地址id获取地址信息
  const address = await Address.findById(addressId)
  //获取商品列表
  const pIds = products.map(p => p.id)
  const productList = await Product.find({
    _id: { $in: pIds }, shopId
  })
  //给商品列表增加销售数量（订单里，每个商品都有销量）
  const productListWithSales = productList.map(p => {
    //商品id
    const id = p._id.toString()
    //找到商品销量
    const filterProducts = products.filter(item => item.id === id)
    if (filterProducts.length === 0) {
      //没有找到匹配的数量，报错
      throw new Error('未找到匹配的销量数据')
    }
    return {
      orderSales: filterProducts[0].num,
      product: p
    }
  })
  // 创建订单
  const newOrder = await Order.create({
    username,
    address,
    shopId,
    shopName,
    isCanceled,
    products: productListWithSales
  })
  return newOrder
}
/**
 * 获取订单列表
 * @param {String} username 
 * @returns Ordre Array
 */
async function getOrderList(username) {
  const list = Order.find({ username }).sort({ _id: -1 })
  return list
}
module.exports = { createOrder, getOrderList }